package com.lin.sqltool.controller;

import com.lin.sqltool.common.BaseQueryController;
import com.lin.sqltool.common.SqlExecutionResult;
import com.lin.sqltool.factory.AIServiceFactory;
import com.lin.sqltool.factory.ConnectionServiceFactory;
import com.lin.sqltool.model.ConnectionInfoModel;
import com.lin.sqltool.service.AIService;
import com.lin.sqltool.service.ConnectionService;
import com.lin.sqltool.utils.CommonUtil;
import com.lin.sqltool.utils.IPUtil;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.control.*;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.lin.sqltool.utils.CommonUtil.showAlert;

public class AIQueryController implements BaseQueryController {

    @FXML
    private ComboBox<String> databaseCombo;


    @FXML
    private TableView<List<String>> resultTable;

    @FXML
    private TextArea resultTextArea;

    @FXML
    private VBox editorVBox;


    private ConnectionInfoModel connectionInfo;

    private ConnectionService connectionService;

    private AIService aiService;

    /**
     * 用于存储每个text的code
     */
    private final Map<AIQueryTextController,AIQueryCodeController> textCodeMap = new HashMap<AIQueryTextController,AIQueryCodeController>();



    /**
     * 设置连接信息
     * @param connectionInfo
     */
    public void setConnectionInfo(ConnectionInfoModel connectionInfo) {
        this.connectionInfo = connectionInfo;
        this.connectionService = ConnectionServiceFactory.getService(connectionInfo.getDatabaseType());
        this.aiService = AIServiceFactory.getService();
        this.databaseCombo.getItems().addAll(connectionService.getDatabases(connectionInfo));
    }

    /**
     * 设置数据库
     * @param database
     */
    public void setDatabaseInfo(String database) {
        this.databaseCombo.setValue(database);
    }




    /**
     * 添加文本
     * @param
     */
    @FXML
    public void handleAddTextCall() {
        try {
            FXMLLoader loader = new FXMLLoader(getClass().getResource("/fxml/AITextEditorHBox.fxml"));
            HBox content = loader.load();
            AIQueryTextController controller = loader.getController();
            controller.setRunButtonAction(new EventHandler<ActionEvent>() {
                @Override
                public void handle(ActionEvent actionEvent) {
                    String text = controller.getTextAreaText();
                    if (text != null && !text.isEmpty()) {
                        String sql = aiService.generateSQL(this.hashCode() + IPUtil.getMacAddress(), connectionInfo, databaseCombo.getValue(), text);
                        if (textCodeMap.get(controller) == null) {
                            try {
                                FXMLLoader loader = new FXMLLoader(getClass().getResource("/fxml/AICodeEditorHBox.fxml"));
                                HBox textContent = loader.load();
                                AIQueryCodeController codeController = loader.getController();
                                codeController.setTextAreaText(sql);
                                //设置运行逻辑
                                codeController.setRunButtonAction(new EventHandler<ActionEvent>() {
                                    @Override
                                    public void handle(ActionEvent actionEvent) {
                                        String selectedDatabase = databaseCombo.getValue();
                                        String sql = codeController.getTextAreaText();
                                        if (selectedDatabase == null) {
                                            showAlert(Alert.AlertType.ERROR, "失败", "请先选择数据库");
                                        }
                                        SqlExecutionResult result = connectionService.executeSql(connectionInfo, selectedDatabase, sql);
                                        resultTable.setVisible(false);
                                        resultTextArea.setVisible(false);

                                        if (result.isQuery()) {
                                            // 显示表格
                                            resultTable.setVisible(true);
                                            resultTable.getColumns().clear();
                                            List<List<String>> tableData = result.getTableData();
                                            if (!tableData.isEmpty()) {
                                                CommonUtil.setTableData(resultTable, tableData);
                                            }
                                        } else {
                                            // 显示文本域
                                            resultTextArea.setVisible(true);
                                            resultTextArea.setText(result.getMessage());
                                        }
                                    }
                                });

                                editorVBox.getChildren().add(editorVBox.getChildren().indexOf(content) + 1, textContent);
                                textCodeMap.put(controller, codeController);
                            } catch (IOException e) {
                                CommonUtil.showAlert(Alert.AlertType.ERROR, "错误", e.getMessage());
                            }
                        }else{
                            AIQueryCodeController codeController = textCodeMap.get(controller);
                            codeController.setTextAreaText(sql);
                        }
                    } else {
                        CommonUtil.showAlert(Alert.AlertType.ERROR, "错误", "请输入内容!");
                    }
                }
            });
            editorVBox.getChildren().add(content);
        } catch (IOException e) {
            CommonUtil.showAlert(Alert.AlertType.ERROR,"错误",e.getMessage());
        }

    }



    /**
     * 添加SQL
     * @param
     */
    @FXML
    public void handleAddSQLCall() {
        try {
            FXMLLoader loader = new FXMLLoader(getClass().getResource("/fxml/AICodeEditorHBox.fxml"));
            HBox content = loader.load();
            AIQueryCodeController controller = loader.getController();
            controller.setRunButtonAction(new EventHandler<ActionEvent>() {
                @Override
                public void handle(ActionEvent actionEvent) {
                    String selectedDatabase = databaseCombo.getValue();
                    String sql = controller.getTextAreaText();
                    if (selectedDatabase == null) {
                        showAlert(Alert.AlertType.ERROR, "失败", "请先选择数据库");
                    }
                    SqlExecutionResult result = connectionService.executeSql(connectionInfo, selectedDatabase, sql);
                    resultTable.setVisible(false);
                    resultTextArea.setVisible(false);

                    if (result.isQuery()) {
                        // 显示表格
                        resultTable.setVisible(true);
                        resultTable.getColumns().clear();
                        List<List<String>> tableData = result.getTableData();
                        if (!tableData.isEmpty()) {
                            CommonUtil.setTableData(resultTable, tableData);
                        }
                    } else {
                        // 显示文本域
                        resultTextArea.setVisible(true);
                        resultTextArea.setText(result.getMessage());
                    }
                }
            });
            editorVBox.getChildren().add(content);
        } catch (IOException e) {
            CommonUtil.showAlert(Alert.AlertType.ERROR,"错误",e.getMessage());
        }
    }


    /**
     * 执行SQL
     *
     * @param sql
     */
    @Override
    public void runSQL(String sql) {
        String selectedDatabase = databaseCombo.getValue();
        if (selectedDatabase == null) {
            showAlert(Alert.AlertType.ERROR, "失败", "请先选择数据库");
        }
        SqlExecutionResult result = connectionService.executeSql(connectionInfo, selectedDatabase, sql);
        resultTable.setVisible(false);
        resultTextArea.setVisible(false);

        if (result.isQuery()) {
            // 显示表格
            resultTable.setVisible(true);
            resultTable.getColumns().clear();
            List<List<String>> tableData = result.getTableData();
            if (!tableData.isEmpty()) {
                CommonUtil.setTableData(resultTable, tableData);
            }
        } else {
            // 显示文本域
            resultTextArea.setVisible(true);
            resultTextArea.setText(result.getMessage());
        }
    }



}
